package com.xiaoc.bulldozer.common.util;

import java.io.IOException;
import java.net.URI;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	private static int CONNECT_TIMEOUT = 100 * 1000;
	private static int SOCKET_TIMEOUT = 100 * 1000;

	private static String execute(HttpRequestBase httpRequestBase, final String encoding){
		CloseableHttpClient httpclient = null;
		try {
			//创建默认的 httpClient 实例
			httpclient = HttpClients.createDefault();
			//设置请求和传输超时时间
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT)
//					.setProxy(new HttpHost("127.0.0.1", 8888))
					.build();
			httpRequestBase.setConfig(requestConfig);
			//执行http请求并接收返回的数据
			String responseText = httpclient.execute(httpRequestBase, new ResponseHandler<String>() {
				@Override
				public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
					try {
						int statusCode = response.getStatusLine().getStatusCode();
						if(statusCode != 200){
							logger.error("鉴权不正确, HTTP返回状态码为 {}", statusCode);
							return null;
						}
						HttpEntity entity = response.getEntity();
						return EntityUtils.toString(entity, encoding);
					} catch (Throwable t) {
						t.printStackTrace();
						logger.error("处理http响应时发生异常", t);
						return null;
					} finally {
						if (response instanceof CloseableHttpResponse) {
							CloseableHttpResponse closeableHttpResponse = (CloseableHttpResponse) response;
							closeableHttpResponse.close();
						}
					}

				}
			});
			return responseText;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("处理http请求时发生异常", e);
			return null;
		} finally {
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


	public static String doGet(String url, List<NameValuePair> formParams, String encoding) {
		try {
			HttpGet httpGet = new HttpGet(url);
			if (formParams != null) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, encoding);
				httpGet.setURI(new URI(httpGet.getURI() + "?" + EntityUtils.toString(entity)));
			}
			return execute(httpGet, encoding);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("http doGet", e);
			return null;
		}
	}


	public static String doPost(String url, String str, String encoding) {
		try {
			HttpPost httpPost = new HttpPost(url);
			StringEntity stringEntity = new StringEntity(str, encoding);
			httpPost.setEntity(stringEntity);
			return execute(httpPost, encoding);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("doPost str异常,错误信息为:", e);
			return null;
		}
	}
	

}
